const app = getApp()

Page({
  data: {
    userInfo: {},
    applications: [],
    statusText: {
      pending: '待审批',
      approved: '已批准',
      rejected: '已拒绝'
    }
  },

  onLoad() {
    // 检查登录状态
    if (!app.checkLogin()) return
    
    // 获取用户信息
    const userInfo = app.globalData.userInfo
    if (!userInfo) {
      wx.showToast({
        title: '请先登录',
        icon: 'none'
      })
      return
    }

    this.setData({ userInfo })
    this.loadApplications()
  },

  onShow() {
    // 每次页面显示时重新加载申请列表
    this.loadApplications()
  },

  // 加载申请列表
  async loadApplications() {
    try {
      const { result } = await wx.cloud.callFunction({
        name: 'getApplications',
        data: {
          type: 'owner'
        }
      })

      if (result.success) {
        // 格式化时间
        const applications = result.data.map(item => ({
          ...item,
          entryTime: app.formatDateTime(new Date(item.entryTime)),
          expectedLeaveTime: app.formatDateTime(new Date(item.expectedLeaveTime)),
          approveTime: item.approveTime ? app.formatDateTime(new Date(item.approveTime)) : ''
        }))

        this.setData({ applications })
      } else {
        wx.showToast({
          title: '加载失败',
          icon: 'none'
        })
      }
    } catch (error) {
      console.error('加载申请列表失败', error)
      wx.showToast({
        title: '加载失败',
        icon: 'none'
      })
    }
  },

  // 跳转到申请页面
  goToApply() {
    wx.navigateTo({
      url: '/pages/owner/application/application'
    })
  },

  // 处理退出登录
  handleLogout() {
    wx.showModal({
      title: '提示',
      content: '确定要退出登录吗？',
      success: (res) => {
        if (res.confirm) {
          app.clearUserInfo()
          wx.redirectTo({
            url: '/pages/login/login'
          })
        }
      }
    })
  }
}) 